package dao.impl;

import dao.DetailDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import utils.ConnUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DetailDaoImpl implements DetailDao {
    private static final Logger logger = LoggerFactory.getLogger(DetailDaoImpl.class);
    /**
     * 通过字段名和商品名查找属性
     * @param fieldName
     * @param goodsName
     * @return List
     */
    @Override
    public List<String> findField(String fieldName,String goodsName) {
        List<String> list = new ArrayList<>();
        String sql = null;
        if(fieldName.equals("color")){
            sql = "select distinct color from goods where name= ?";
        }else if(fieldName.equals("capacity")){
            sql = "select distinct phone_parameter.capacity \n" +
                    "from phone_parameter join goods \n" +
                    "on goods.id = phone_parameter.goods_id \n" +
                    "where goods.name= ? ";
        }else if(fieldName.equals("network_type")){
            sql = "select distinct phone_parameter.network_type \n" +
                    "from phone_parameter join goods \n" +
                    "on goods.id = phone_parameter.goods_id \n" +
                    "where goods.name= ? ";
        }
        Connection conn = ConnUtil.getConnection();
        PreparedStatement pr = null;
        ResultSet rs = null;
        try {
            pr = conn.prepareStatement(sql);
            pr.setString(1,goodsName);
            rs = pr.executeQuery();
            while(rs.next()){
                String s = rs.getString(fieldName);
                list.add(s);
            }
        } catch (SQLException e) {
           logger.error("DetailDaoImpl中的findField方法异常",e);
        }

        return list;
    }
}
